package edu.bmstu.rslab;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.geom.Point2D;

/**
 * Created by Chikh (using IntelliJ IDEA).
* Date: 15.05.2009
* Time: 15:01:28
*/
class selectDirectionMaskAction extends AbstractAction {
    private final VideoPanel videoPanel;
    private final Camera camera;
    private final Action setPathAction;
    private final Detector directionDetector;
    private boolean isFirstTime = true;

    public selectDirectionMaskAction(VideoPanel videoPanel, Camera camera, Action setPathAction,
                                     Detector directionDetector) {
        super("Select direction mask");
        this.videoPanel = videoPanel;
        this.camera = camera;
        this.setPathAction = setPathAction;
        this.directionDetector = directionDetector;
        setEnabled(false);
    }

    public void actionPerformed(ActionEvent e) {
        setEnabled(false);
        final MouseMotionListener mouseMotionHandler = new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                videoPanel.selectingArea(videoPanel.getScaledPoint(e.getPoint()));
            }
        };
        videoPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                videoPanel.beginSelecting(videoPanel.getScaledPoint(e.getPoint()));
                videoPanel.addMouseMotionListener(mouseMotionHandler);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                videoPanel.removeMouseMotionListener(mouseMotionHandler);
                if (isFirstTime) {
                    videoPanel.showMagnifiedImage(videoPanel.getScaledPoint(e.getPoint()));
                    isFirstTime = false;
                }
                else {
                    videoPanel.removeMouseListener(this);
                    directionDetector.setMask(videoPanel.getSelectedMask(videoPanel.getScaledPoint(e.getPoint())));
                    BufferedImage video = camera.getImage();
                    Point2D detectedDirection = directionDetector.detect(video);
                    videoPanel.setDetectedDirection(detectedDirection);
                    setPathAction.setEnabled(true);
                }
            }
        });
    }
}
